﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

using Microsoft.Win32;

namespace pyTivoMetadataManager
{
    public sealed class SettingsSingleton
    {
        /* Some unconfigurable variables. */
        private const string REGISTRY_KEY = "Software\\pyTivoMetadataManager";

        /* Registry keys */
        private const string REGVAL_MEDIAPATH = "mediaPath";

        private static SettingsSingleton instance = null;
        private static readonly object padlock = new object();

        public static SettingsSingleton Instance
        {
            get
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new SettingsSingleton();
                    }
                    return instance;
                }
            }
        }

        public string MediaPath = AppDomain.CurrentDomain.BaseDirectory;

        private SettingsSingleton()
        {
            RegistryKey key;

            if ((key = Registry.CurrentUser.OpenSubKey(REGISTRY_KEY, false)) == null)
            {
                key = Registry.CurrentUser.CreateSubKey(REGISTRY_KEY);
            }
            if (key.GetValue(REGVAL_MEDIAPATH) != null)
            {
                this.MediaPath = (string)key.GetValue(REGVAL_MEDIAPATH);
            }
        }

        public void Commit()
        {
            try
            {
                RegistryKey key;
                if ((key = Registry.CurrentUser.OpenSubKey(REGISTRY_KEY, true)) == null)
                {
                    key = Registry.CurrentUser.CreateSubKey(REGISTRY_KEY);
                }
                key.SetValue(REGVAL_MEDIAPATH, this.MediaPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error writing settings to registry", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
